# coding:utf-8
import sys;sys.path.append("..")
from urlparse import urlparse, urljoin, urlunparse
import requests
import threading
import argparse
# 192.168.1.1
screenLock = threading.Semaphore(value=1)


# ip：当前靶机网段
# index 遍历第几位，0，1，2，3
def get_ip_list(ip,index=3):
    splitip = ip.split(".")
    ip_list=[]
    for i in range(255):
        splitip[index]=str(i)
        iptemp=splitip[0]+"."+splitip[1]+"."+splitip[2]+"."+splitip[3]
        ip_list.append(iptemp)
    return ip_list

# 保存ip到文件中
# ip:存入的字段
# ippath:文件的名字
def save_ip(ip,ippath="./ip"):
    f=open(ippath,"a+")
    f.write(ip+"\n")
    f.close()


# 检测ip是否存活
# ip:需检测的ip地址 e.g. 192.168.1.1
# port: 检测的端口
def clean_ip(ip,port=80):
    try:
        r=requests.head("http://"+ip+":"+str(port),timeout = 3)
        screenLock.acquire()
        print("[+] "+ip+" status_code:"+str(r.status_code))
        save_ip(ip)
    except:
        pass
    finally:
        screenLock.release()

# 检测整个列表的ip是否存活。
# ip_list:ip列表
# threadNumber: 线程
# port: 检测的端口
def clean_ip_list(ip_list,threadNumber=10,port=80):
    threads=[]
    for ip in ip_list:
        threads.append(threading.Thread(target=clean_ip,args=(ip,port,)))
    for thread in threads:
        thread.start()
        while True:
            if (len(threading.enumerate()) < threadNumber):
                break


if __name__=="__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument("ip", help="Your target ip.",
                        action="store")
    parser.add_argument("-p", "--port", help="Your target port.",
                        action="store",default=80,type=int)

    parser.add_argument("-i", "--index", help="The index of ip split with '.'.",
                        action="store", default=2, type=int, choices=[0,1,2,3])
    args = parser.parse_args()

    try:
        ip_list = get_ip_list(args.ip,args.index)
        clean_ip_list(ip_list,args.port)
    except:
        print("[-] Please check your input.")